package com.yunkaweilai.android.base;


import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.multidex.MultiDex;

import com.baidu.mobstat.StatService;
import com.bilibili.boxing.BoxingCrop;
import com.bilibili.boxing.BoxingMediaLoader;
import com.github.lazylibrary.util.PreferencesUtils;
import com.google.gson.Gson;
import com.orhanobut.logger.LogLevel;
import com.orhanobut.logger.Logger;
import com.yunkaweilai.android.BuildConfig;
import com.yunkaweilai.android.activity.MainActivity;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.function.photopick.BoxingGlideLoader;
import com.yunkaweilai.android.function.photopick.BoxingUcrop;
import com.yunkaweilai.android.function.update.CustomApkFileCreator;
import com.yunkaweilai.android.function.update.CustomStrategy;
import com.yunkaweilai.android.function.update.CustomUpdateCreatorWjx;
import com.yunkaweilai.android.function.update.DialogDownloadCreator;
import com.yunkaweilai.android.function.update.NotificationInstallCreator;
import com.yunkaweilai.android.function.update.OkhttpCheckWorker;
import com.yunkaweilai.android.function.update.OkhttpDownloadWorker;
import com.yunkaweilai.android.model.AppRuleModel;
import com.yunkaweilai.android.model.AppUpdateBean;
import com.yunkaweilai.android.model.PayTypeModel;
import com.yunkaweilai.android.model.login.ShiftModel;
import com.yunkaweilai.android.model.login.UserInfoModel;
import com.yunkaweilai.android.model.operation.CreateSelectedGoodsModel;
import com.yunkaweilai.android.model.shop.ShopSkuInfoModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.utils.SoundPlayUtils;

import org.lzh.framework.updatepluginlib.UpdateConfig;
import org.lzh.framework.updatepluginlib.model.CheckEntity;
import org.lzh.framework.updatepluginlib.model.HttpMethod;
import org.lzh.framework.updatepluginlib.model.Update;
import org.lzh.framework.updatepluginlib.model.UpdateChecker;
import org.lzh.framework.updatepluginlib.model.UpdateParser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


public class BaseApplication extends Application {

    private static BaseApplication instance;
    public static String token = "";//token暂时使用的
    public static String member_status = "";//新增会员的锁定与否
    public static ShiftModel shiftModel;
    public static boolean is_open_lock_member = false;
    public static PayTypeModel payModel ;//支付方式
    public static ArrayList<CreateSelectedGoodsModel.DataBean.GoodsListBean> jiciGoodsList;
    private boolean DEBUG = BuildConfig.DEBUG;
    public static AppRuleModel.DataBean.InfoBean appRuleModel;
    public static int APP_CODE = 0;
    public static String Zhanghao = "";

    public static AppRuleModel.DataBean.InfoBean getAppRuleModel() {
        return appRuleModel;
    }

    public static ArrayList<CreateSelectedGoodsModel.DataBean.GoodsListBean> getJiciGoodsList() {
        return jiciGoodsList;
    }

    public static ShiftModel getShiftModel() {
        return shiftModel;
    }

    public static UserInfoModel.DataBean.StoreEmployeeInfoBean userInfo;

    public static Map<String,ShopSkuInfoModel> selectedMaps = new HashMap<>();


    public static UserInfoModel.DataBean.StoreEmployeeInfoBean getUserInfo() {
        return userInfo;
    }

    public static Map<String, ShopSkuInfoModel> getSelectedMaps() {
        return selectedMaps;
    }
    public static void cleanSelectedMaps(){
        selectedMaps.clear();
    }

    public static PayTypeModel getPayModel(){
        return payModel;
    }
    public static String getToken(){return token;}

    public static BaseApplication getInstance() {
        return instance;
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        PreferencesUtils.PREFERENCE_NAME = CommonConstants.PREFERENCE_NAME;//设置Preferences名字
        initLog();//初始化log
        HttpRequest.initClient();//初始化网络请求
        BoxingMediaLoader.getInstance().init(new BoxingGlideLoader());//初始化相册
        BoxingCrop.getInstance().init(new BoxingUcrop());//初始化图片裁剪
        initUpdate();//初始化app自动更新
        StatService.start(this);
        SoundPlayUtils.init(this);
        Thread.setDefaultUncaughtExceptionHandler(restartHandler); // 程序崩溃时触发线程  以下用来捕获程序崩溃异常
//        setupLeakCanary();//内存检测
    }

    // 创建服务用于捕获崩溃异常
    private Thread.UncaughtExceptionHandler restartHandler = new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread thread, Throwable ex) {
            restartApp();//发生崩溃异常时,重启应用
        }
    };
    //重启App
    public void restartApp(){
        Intent intent = new Intent(this,MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        this.startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());  //结束进程之前可以把你程序的注销或者退出代码放在这段代码之前
    }
//
//    /**
//     * 初始化 内存泄漏检测
//     */
//    protected RefWatcher setupLeakCanary() {
//        if (LeakCanary.isInAnalyzerProcess(this)) {
//            return RefWatcher.DISABLED;
//        }
//        return LeakCanary.install(this);
//    }

    private void initLog() {
        if (DEBUG) {
            Logger.init().logLevel(LogLevel.FULL);
        } else {
            Logger.init().logLevel(LogLevel.NONE);
        }
    }

    /**
     * 初始化自动更新设置
     */
    private void initUpdate() {

        UpdateConfig.getConfig()
                .init(this)
                .checkEntity(new CheckEntity().setMethod(HttpMethod.POST).setUrl(Api.APP_UPDATE))
                .jsonParser(new UpdateParser() {
                    @Override
                    public Update parse(String response) {
                        AppUpdateBean.DataBean.InfoBean uplistEntity = new Gson().fromJson(response, AppUpdateBean.class).getData().getInfo();
                        Update update = new Update(response);
                        // 此apk包的更新时间
                        update.setUpdateTime(Long.parseLong(uplistEntity.getCreate_time()));
                        // 此apk包的下载地址
                        update.setUpdateUrl(uplistEntity.getApk_url());
                        // 此apk包的版本号
                        update.setVersionCode(Integer.parseInt(uplistEntity.getVersion_code()));
                        // 此apk包的版本名称
                        update.setVersionName(uplistEntity.getVersion_name() + "/" + uplistEntity.getSize());
                        // 此apk包的更新内容
                        update.setUpdateContent(uplistEntity.getDescription());
                        // 此apk包是否为强制更新
                        if ("1".equals(uplistEntity.is_update())){
                            update.setForced(true);
                        }else{
                            update.setForced(false);
                        }
                        // 是否显示忽略此次版本更新按钮
//                        update.setIgnore(true);
                        return update;
                    }
                })
                .checkWorker(new OkhttpCheckWorker())// 自定义更新接口的访问任务
                .downloadWorker(new OkhttpDownloadWorker())
                .downloadDialogCreator(new DialogDownloadCreator())
                .strategy(new CustomStrategy())
                .fileCreator(new CustomApkFileCreator())
                .updateDialogCreator(new CustomUpdateCreatorWjx())//检查到有更新时弹出
                .updateChecker(new UpdateChecker() {
                    @Override
                    public boolean check(Update update) {
                        int versionCode = update.getVersionCode();
                        PackageInfo pi = null;
                        PackageManager pm = getPackageManager();
                        try {
                            pi = pm.getPackageInfo(getPackageName(),
                                    PackageManager.GET_CONFIGURATIONS);
                        } catch (PackageManager.NameNotFoundException e) {
                            e.printStackTrace();
                        }
                        if (pi != null){
                            if (versionCode > pi.versionCode){
                                return true;
                            }
                        }else{
                            if (versionCode > CommonConstants.VERSION_CODE){
                                return true;
                            }
                        }
                        return false;
                    }
                })

                .installDialogCreator(new NotificationInstallCreator());


    }

}










